#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Thibauld Favre <tfavre@gmail.com>
#
# Author:
#  Thibauld Favre
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA

import urllib
original_open_https = urllib.URLopener.open_https
import time
import os
from smcagent.api import SMCApi
from smcagent.request import Requests
urllib.URLopener.open_https = original_open_https

config_cache = os.path.expanduser('~/.savemyconf')
download_cache = os.path.expanduser('~/.savemyconf/files')
code_cache = os.path.expanduser('~/.savemyconf/code')
data_cache = os.path.expanduser('~/.savemyconf/data')

class SMCAgent:
    listen = False
    def __init__(self, key):
        self.__api = SMCApi(key)
        self.__requests = Requests()
        self.__valid_token = False
        self.__sleep_time = 4
        self.__max_time = 600
        if not os.path.exists(os.path.expanduser(code_cache)):
            os.makedirs(os.path.expanduser(code_cache))
        if not os.path.exists(os.path.expanduser(data_cache)):
            os.makedirs(os.path.expanduser(data_cache))

    def checkToken(self):
        self.__valid_token = self.__api.checkTokenValidity()
        return self.__valid_token

    def getAuthUrl(self):
        return self.__api.auth_url

    def register(self):
        SMCAgent.listen = True
        if not self.__valid_token:
            time_spent_trying=0
            while not self.__api.getToken() and SMCAgent.listen and time_spent_trying<self.__max_time:
                time.sleep(self.__sleep_time)
                time_spent_trying+=self.__sleep_time
        self.__valid_token = (SMCAgent.listen and time_spent_trying<self.__max_time)
        return self.__valid_token

    def run(self):
        if self.__valid_token:
            SMCAgent.listen = True
            while (SMCAgent.listen):
                nb = self.__api.reqAvailable();
                if nb > 0:
                    req = self.__api.getRequest(self.req_finished)
                    self.__requests.add(req)
                    self.__requests.schedule()
            self.__requests.finish()

    def req_finished(self,id,end_status):
        self.__requests.terminated(id)
        self.__api.reqEndStatus(id,end_status)

